/**
 * kafka 接口请求文件
*/
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { jumpToLogin, notifiyError } from '@/utils/public'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  validateStatus: function(status) {
    return (status >= 200 && status < 300) || status === 302
  },
  timeout: 0// request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 使用mock数据
    if (config.baseURL === 'mock') {
      config.baseURL = process.env.VUE_APP_MOCK_API
    }
    // 不使用token的接口
    if (config.noToken !== 'cms') {
      if (getToken()) {
        config.headers['Authorization'] = 'Bearer ' + getToken()
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 下载文件
    if (response.config.url.includes('/dfile/file/download?fileUrl')) {
      return response
    }
    // 登录获取token
    if (response.config.url.includes('/auth/oauth/token')) {
      return response
    }
    return res
  },
  error => {
    // 登录获取token
    if (error.config.url.includes('/auth/oauth/token')) {
      return error.response
    }
    if (error.response && error.response.status !== 500) {
      error.response.data.message ? notifiyError(error.response.data.message) : ''
      if (error.response.status === 401) {
        // token失效
        jumpToLogin()
      }
    } else {
      // notifiyError(error.message.includes('timeout') ? '连接超时' : error.message)
    }
    return Promise.reject(error)
  }
)

export default service
